<template>
  <div class="app-container">
    <NormalForm pageTitle="部门管理" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt" @handleQuery="handleQuery" @handleReset="handleReset" />
    <div class="g-card" style="padding: 0 20px 20px 20px">
      <div class="right-btn" style="margin-right: 0">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['system:config:add']">新增</el-button>
      </div>
      <el-table v-loading="loading" :data="deptList" row-key="deptId" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="部门名称" min-width="180"></el-table-column>
        <el-table-column prop="orderNum" label="排序" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center" min-width="120">
          <template slot-scope="scope">
            <span>{{ stateOpt[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"  min-width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="260">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dept:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
              v-hasPermi="['system:dept:add']">新增</el-button>
            <el-button v-if="scope.row.parentId != 0" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="updateVisible" width="600px" append-to-body :close-on-click-modal="false" :show-close="false">
      <el-form ref="updateForm" :model="updateForm" :rules="updateRules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="updateForm.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="updateForm.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="updateForm.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="updateForm.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="updateForm.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="updateForm.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="updateForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态" prop="status">
              <el-radio-group v-model="updateForm.status">
                <el-radio v-for="item in enumOpt.stateList" :key="item.dictValue" :label="item.dictValue">
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
        <el-button @click="updateCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      queryForm: {
        deptName: '',
        status: null
      },
      formList: [
        {
          label: '部门名称',
          value: '',
          prop: 'deptName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '部门状态',
          value: '',
          prop: 'status',
          type: 'SELECT',
          emunName: 'stateList'
        },
      ],
      enumOpt: {
        stateList: [],
      },
      stateOpt: {},
      loading: true,
      deptList: [],
      title: "",
      updateVisible: false,
      // 问卷参数
      updateForm: {
        parentId: null,
        deptName: null,
        orderNum: 0,
        leader: null,
        phone: null,
        email: null,
        status: '0',
      },
      // 问卷校验
      updateRules: {
        parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
        deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
        orderNum: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
        email: [{ type: "email", message: "'请输入正确的邮箱地址", trigger: ["blur", "change"] }],
        phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
      },
      // 部门树选项
      deptOptions: [],
    };
  },
  created() {
    this.getDicts("sys_normal_disable").then((res) => {
      if (res.code == 200) {
        this.enumOpt.stateList = res.data;
        res.data.forEach(item => {
          this.stateOpt[item.dictValue] = item.dictLabel;
        })
      }
    });
    this.handleQuery();
  },
  methods: {
    /** 查询部门列表 */
    handleQuery() {
      this.loading = true;
      listDept(this.queryForm).then((res) => {
        this.deptList = this.handleTree(res.data, "deptId");
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryForm = {
        deptName: '',
        status: null
      },
      this.handleQuery();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    // 取消按钮
    updateCancel() {
      this.updateVisible = false;
      this.$refs.updateForm.resetFields();
      this.updateForm = {
        parentId: null,
        deptName: null,
        orderNum: 0,
        leader: null,
        phone: null,
        email: null,
        status: '0',
      };
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      row && (this.updateForm.parentId = row.deptId);
      this.updateVisible = true;
      this.title = "添加部门";
      listDept().then((res) => {
        this.deptOptions = this.handleTree(res.data, "deptId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getDept(row.deptId).then((response) => {
        this.updateForm = response.data;
        this.updateVisible = true;
        this.title = "修改部门";
      });
      listDeptExcludeChild(row.deptId).then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 提交按钮 */
    updateSubmit() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          if (this.updateForm.deptId != undefined) {
            updateDept(this.updateForm).then((response) => {
              if (response.code === 200) {
                this.$message.success("修改成功");
                this.updateCancel()
                this.handleQuery();
              }
            });
          } else {
            addDept(this.updateForm).then((response) => {
              if (response.code === 200) {
                this.$message.success("新增成功");
                this.updateCancel()
                this.handleQuery();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除名称为"' + row.deptName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delDept(row.deptId);
        })
        .then(() => {
          this.handleQuery();
          this.$message.success("删除成功");
        })
        .catch(function () { });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";
</style>
